import axios from 'axios'
import router from '@/router'
import { Toast } from 'vant'
import store from '@/store'

// 创建请求实例
const instance = axios.create({
  baseURL: '/api',
  // 指定请求超时的毫秒数
  timeout: 6000000,
  // 表示跨域请求时是否需要使用凭证
  withCredentials: false
})

// 前置拦截器（发起请求之前的拦截）
instance.interceptors.request.use(
  (config) => {
    const token = store.getters.satoken
    if (token) config.headers.satoken = `Bearer ${token}`
    Toast.loading({
      message: '加载中...',
      forbidClick: true,
      overlay: true,
      duration: 0
    })
    return config
  },
  (error) => {
    return Promise.reject(error)
  }
)

// 后置拦截器（获取到响应时的拦截）
instance.interceptors.response.use(
  (response) => {
    /**
     * 根据你的项目实际情况来对 response 和 error 做处理
     * 这里对 response 和 error 不做任何处理，直接返回
     */
    if (response.data.code) {
      const { code, msg } = response.data
      let errMessage = ''
      switch (code) {
        case 200: //正常
          break
        case 401: //未登录
          Toast.clear()
          store.dispatch('clearLogin')
          router.push(
            '/login?returnUrl=' +
              encodeURIComponent(router.currentRoute.fullPath)
          )
          break
        default:
          errMessage = msg
      }
      Toast.clear()
      if (errMessage) {
        Toast.fail(errMessage)
      }
    }
    return response.data
  },
  (error) => {
    const { response } = error
    if (response && response.status == 401) {
      Toast.clear()
      // token失效
      store.dispatch('clearLogin')
      router.push(
        '/login?returnUrl=' + encodeURIComponent(router.currentRoute.fullPath)
      )
    }
    if (response && response.data) {
      Toast.clear()
      return Promise.reject(error)
    }
    const { message } = error
    console.error(message)
    Toast.clear()
    return Promise.reject(error)
  }
)

// 导出常用函数

/**
 * @param {string} url
 * @param {object} data
 * @param {object} params
 */
export const post = (url, data = {}, params = {}) => {
  return instance({
    method: 'post',
    url,
    data,
    params
  })
}

/**
 * @param {string} url
 * @param {object} params
 */
export const get = (url, params = {}) => {
  return instance({
    method: 'get',
    url,
    params
  })
}

/**
 * @param {string} url
 * @param {object} data
 * @param {object} params
 */
export const put = (url, data = {}, params = {}) => {
  return instance({
    method: 'put',
    url,
    params,
    data
  })
}

/**
 * @param {string} url
 * @param {object} params
 */
export const _delete = (url, params = {}) => {
  return instance({
    method: 'delete',
    url,
    params
  })
}

export default instance
